package com.ciaojian.bytedance.policy.impl.coupon;


import cn.hutool.core.map.MapUtil;
import com.ciaojian.core.model.MemberDiscount;
import com.ciaojian.core.service.ICouponDiscount;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;

/**
 * 首单优惠
 *
 * @author Atlakyn
 */
@Slf4j
@Service
public class ShoudanDiscount implements ICouponDiscount<Map<String, Object>> {


    /**
     * 首单优惠
     * 在用户购买会员卡后会获得一定次数的优惠价
     * 优惠力度和次数由后台设置
     *
     * @param couponMap 优惠信息 {memberDiscountId:用户-首单折扣id,userIdOfOrder:订单里的订单id}
     * @param amount    原价
     * @return 优惠后的价格
     */
    @Override
    public BigDecimal discountAmount(Map<String, Object> couponMap, BigDecimal amount) {
        // 取出 用户-优惠 id
        Integer memberDiscountId = MapUtil.getInt(couponMap, "memberDiscountId");
        // 取出订单的 userId
        Integer userIdOfOrder = MapUtil.getInt(couponMap, "userIdOfOrder");

        // 会员优惠
        MemberDiscount memberDiscount = new MemberDiscount().selectById(memberDiscountId);
        // 校验优惠是否有效
        if (memberDiscount == null || memberDiscount.getOrderId() != null) {
            log.info(">>>优惠不存在或已被使用>>>memberDiscount={}", memberDiscount);
            return amount;
        }
        // 校验 memberDiscount 的 userId 和 order 的 userId 是否一致
        if (!memberDiscount.getUserId().equals(userIdOfOrder)) {
            log.info(">>>优惠所属用户和订单用户不一致>>>memberDiscount={},order2.getUserId()={}",
                    memberDiscount,
                    userIdOfOrder);
            return amount;
        }

        // 原价格优惠后的价格
        amount = amount.subtract(memberDiscount.getAmount());
        return amount.compareTo(BigDecimal.ZERO) < 0 ? BigDecimal.ZERO : amount;
    }

}
